﻿using System;
using System.Windows;

namespace FreeGoo.WpfDemo
{
    public partial class GameControl
    {
        private int _scrollBorderSize;
        private Point _mousePoint;
        private Point _mouseDownPos;
        private Point _scrollStartPos;
        private int ScrollStep { get; set; }
        private int TimeRampup { get; set; }

        private void SetupScrolling()
        {
            _scrollBorderSize = 30;
            ScrollStep = 10;
            TimeRampup = 1500;
        }

        private double GetTimeSpeedup()
        {
            if (!_scrollStopwatch.IsRunning)
            {
                _scrollStopwatch.Reset();
                _scrollStopwatch.Start();
            }

            double rampValue = Math.Max(0, Math.Min(1, _scrollStopwatch.Elapsed.TotalMilliseconds / TimeRampup));
            return 0.2 + 0.8 * rampValue;
        }

        private void UpdateScroll()
        {
            double timeSpeedup = 1;
            bool scrolled = false;

            bool mouseOver;
#if !SILVERLIGHT
            mouseOver = ScrollViewer.IsMouseOver;
#else
            mouseOver = false;
#endif
            if (mouseOver)
            {
                if (_mousePoint.X < _scrollBorderSize)
                {
                    timeSpeedup = GetTimeSpeedup();
                    ScrollViewer.ScrollToHorizontalOffset(ScrollViewer.HorizontalOffset - ScrollStep * timeSpeedup);
                    scrolled = true;
                }
                else if (_mousePoint.X > ScrollViewer.RenderSize.Width - _scrollBorderSize)
                {
                    timeSpeedup = GetTimeSpeedup();
                    ScrollViewer.ScrollToHorizontalOffset(ScrollViewer.HorizontalOffset + ScrollStep * timeSpeedup);
                    scrolled = true;
                }

                if (_mousePoint.Y < _scrollBorderSize)
                {
                    timeSpeedup = GetTimeSpeedup();
                    ScrollViewer.ScrollToVerticalOffset(ScrollViewer.VerticalOffset - ScrollStep * timeSpeedup);
                    scrolled = true;
                }
                else if (_mousePoint.Y > ScrollViewer.RenderSize.Height - _scrollBorderSize)
                {
                    timeSpeedup = GetTimeSpeedup();
                    ScrollViewer.ScrollToVerticalOffset(ScrollViewer.VerticalOffset + ScrollStep * timeSpeedup);
                    scrolled = true;
                }
            }

            if (_scrollStopwatch.IsRunning && !scrolled)
            {
                _scrollStopwatch.Stop();
            }
        }
    }
}
